import { defineStore } from 'pinia'
import request from '@/utils/request'
import { CartItem, ApiRes } from '@/types/data'
import useStore from '..'
const useCartStore = defineStore('cart', {
  // persist: true,
  persist: {
    key: 'rabbit-cart-93'
  },
  // 状态
  state () {
    return {
      list: [] as CartItem[] // 购物车数组
    }
  },
  // 计算
  getters: {
    // 🔑登录状态
    isLogin (): boolean {
      const { user } = useStore()
      return !!user.profile.token
    },
    // 计算有效商品列表 isEffective = true  filter
    effectiveList (): CartItem[] {
      return this.list.filter((item) => item.stock > 0 && item.isEffective)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveListCounts (): number {
      return this.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    effectiveListPrice (): string {
      return this.effectiveList
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },
    selectedList (): CartItem[] {
      return this.effectiveList.filter(it => it.selected)
    },
    selectedCount (): number {
      return this.effectiveList.filter(it => it.selected).length
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    selectedPrice (): string {
      return this.effectiveList.filter(it => it.selected)
        .reduce((sum, item) => sum + item.count * Number(item.nowPrice), 0)
        .toFixed(2)
    },
    isAllSelected (): boolean {
      return (
        this.effectiveList.length !== 0 &&
          this.effectiveList.every((item) => item.selected)
      )
    }

  },
  // 方法
  actions: {
    async addCart (data: CartItem) {
      if (this.isLogin) {
        await request.post('/member/cart', { skuId: data.skuId, count: data.skuId })
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        console.log('本地添加购物车', data)
        // 1. 判断购物车列表中是否有该商品数据
        const goods = this.list.find((item) => item.skuId === data.skuId)
        if (goods) {
          // 2. 如果商品存在，直接把数量加起来
          goods.count += data.count
        } else {
          // 3. 如果商品不存在，直接添加该商品
          this.list.unshift(data)
        }
      }
    },
    // 获取购物车列表
    async getCartList () {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        this.list = res.data.result
      } else {
        console.log('本地获取购物车')
      }
    },
    // 删除购物车商品
    async delCart (skuIds: string[]) {
      if (this.isLogin) {
        await request.delete('/member/cart', {
          data: { ids: skuIds }
        })
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        this.list = this.list.filter((item) => !skuIds.includes(item.skuId))
      }
    },
    // 修改购物车商品
    async updateCart (
      skuId: string,
      data: { selected?: boolean; count?: number }
    ) {
      if (this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        // 重新获取最新购物车列表
        this.getCartList()
      } else {
        const goods = this.effectiveList.find((item) => item.skuId === skuId)
        if (data.selected !== undefined) {
            goods!.selected = data.selected
        }
        if (data.count !== undefined) {
            goods!.count = data.count
        }
      }
    },
    // 修改全选或者全不选
    async updateCartAllSelected (isSelected: boolean) {
      await request.put('/member/cart/selected', {
        selected: isSelected
      })
      // 获取购物车列表
      this.getCartList()
    },
    // 清空购物车
    clearCart () {
      // 退出登录需清空购物车
      this.list = []
    },
    // 合并购物车
    async mergeLocalCart () {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  }
})

export default useCartStore
